//
//  LandmarkList.swift
//  Landmarks
//
//  Created by XN on 2019/6/5.
//  Copyright © 2019 pc. All rights reserved.
//

import SwiftUI


/// 列表
struct LandmarkList : View {
    
    @Environment(ModelData.self) var modelData
    
    /// 仅展示收藏
    @State private var showFavoritesOnly = false
    
    /// 数据过滤
    private var filterLandmarks:[Landmark] {
        modelData.landmarkData.filter { $0.isFavorite == true || !showFavoritesOnly }
    }
    
    /// 转场设置
    @State private var selectIndex:Int = 0
    @State private var _index:Int? = nil
    
    var body: some View {
        NavigationView {
            List{
                Toggle(isOn: $showFavoritesOnly, label: {
                    Text("Favorites Only")
                })
                
                if selectIndex == 0 {
                    ForEach(filterLandmarks) { landmark in
                        NavigationLink {
                            LandMarkDetail(landmark: landmark)
                        } label: {
                            LandmarkRow(landmark: landmark)
                        }
                    }
                }
                else{
                    ForEach(filterLandmarks.indices,id:\.self) { index in
                        LandmarkRow(landmark: filterLandmarks[index])
                            .onTapGesture {
                                _index = index
                                debugPrint("onTapGesture:{\(index),\(String(describing: _index))}")
                            }
                    }
                    .sheet(isPresented: .constant(selectIndex > 0 && _index != nil),
                           onDismiss: {
                        _index = nil
                    },
                           content: {
                        if _index != nil && filterLandmarks.count > _index! {
                            LandMarkDetail(landmark: filterLandmarks[_index!])
                        }
                    })
                }
            }
            .navigationBarTitle("Landmarks", displayMode: .large)
            .navigationBarItems(trailing: SegmentButton(selectIndex:$selectIndex))
            .animation(.easeInOut, value: 0.5)
        }
    }
}

#Preview {
    let modelData = ModelData()
    return LandmarkList()
        .environment(modelData)
}
